<template>
  <div>
  	<el-dialog title="添加商品" :visible.sync="addVisible" width="30%" :before-close="closeAddGoods" @open="opendEnd">
  		<el-form :model="goodsList" ref="addClassify" label-width="100px">
        <el-form-item label="商品名称" prop="goodsName" :rules="[
              { required: true, message: '请输入商品名称', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="单价" prop="price" :rules="[
              { required: true, message: '请输入单价', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.price" placeholder="请输入单价"></el-input>
        </el-form-item>

        <el-form-item label="规格" prop="specification" :rules="[
              { required: true, message: '请输入规格', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.specification" placeholder="请输入规格"></el-input>
        </el-form-item>

  			<el-form-item label="类型图片" prop="goodsImg" :rules="[
              { required: true, message: '请插入图片', trigger: 'blur' },
            ]">
          <el-input v-show="false" v-model="goodsList.goodsImg"/>
          <el-upload
            class="upload-demo"
            ref="upload"
            list-type="picture"
            action=""
            :limit="1"
            :on-change="imgVaildata"
            :auto-upload="false"
            :on-remove="handleRemove"
            :before-upload="beforeUploadHandle"
            :http-request="handleUploadForm"
            >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="隶属分类" prop="classifyId" :rules="[
             { required: true, message: '请选择分类', trigger:'blur'},
           ]">
              <el-select v-model="goodsList.classifyId" placeholder="可选择分类" clearable>
                <el-option
                  v-for="item in classifyOptions"
                  :key="item.classifyId"
                  :label="item.classifyName"
                  :value="item.classifyId"
                  v-if="item.classifyType==0">
                </el-option>
              </el-select>
        </el-form-item>
  		</el-form>
  		<span slot="footer" class="dialog-footer">
  			<el-button @click="closeAddGoods">取 消</el-button>
  			<el-button type="primary" @click="submitUpload('addClassify')">确 定</el-button>
  		</span>
  	</el-dialog>
  </div>
</template>
<script>
  export default {
  	name: "",
  	props: ["addVisible","addOptions"],
  	data() {
  		return {
  			goodsList: {
          goodsName:"",
          price:null,
          specification:null,
          goodsImg:"",
          classifyId:"",
  			},
        classifyOptions:{},
        //是否允许执行方法
        goFunction:true,
  		}
  	},
    methods: {
      //需要等待dialog 打开完毕后 在金数据渲染
      opendEnd(){
        //设置隶属分类下拉框的值
        this.classifyOptions = this.$props.addOptions
      },
      //设置关闭添加页面方法
      closeAddGoods() {
          //关闭前还原文本框默认值
          this.clearData()
      		this.$parent.addVisible = false
      },
      //清除文本框数据，返回相对应文本框的值
      clearData(){
          this.goodsList={
            goodsName:"",
            price:null,
            specification:null,
            goodsImg:"",
            classifyId:"",
          }
          this.clearFiles()
      },
      //清空图片方法
      clearFiles () {
          this.$refs['upload'].clearFiles();
      },
      //判断表单数据是否为空
       //并提交数据
      submitUpload(params) {
        console.log("触发判断事件")
        var self = this
        this.$refs[params].validate((valid) => {
       	if (valid) {
           self.$refs.upload.submit();
       	} else {
       		console.log('error submit!!');
       		return false;
       	}
       });
      },
      //验证图片是否为空
      imgVaildata(file, fileList){
          var self = this
          console.log('vue 图片上传钩子函数')
          self.goodsList.goodsImg=file.name
          console.log(self.goodsList.goodsImg)
          if(file.name==null || file.name==""){
            self.goodsList.goodsImg=null
          }
      },
      //触发删除事件
      handleRemove(file, fileList) {
        console.log("触发删除事件")
        if(file){
          this.goodsList.goodsImg=""
        }
        console.log(file, fileList);
      },
      //上传文件前执行的方法,判断文件格式
      beforeUploadHandle(file) {
        console.log("执行上传前方法")
        if (
            file.type !== "image/png" &&
            file.type !== "image/jpeg"
        ) {
          this.$message.error("只支持.jpg、.jpeg、.jpe、.png文件！");
          return false;
        }
      },



      //执行添加方法
      handleUploadForm(param) {
        console.log(param)
        console.log(JSON.stringify(this.goodsList))
        let self = this
        var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
        var page = sessionStorage.getItem("page")
        //是否允许执行方法
        this.goFunction=true
        /*
            1.检查商品名称是否包含空格
        */
        // 检测输入的数据中是否存在空格
        var goodsName = this.goodsList.goodsName
        if(goodsName.split(" ").length==1){

          /*
              2.检查单价和规格是否是符合规格的
          */
          /* 2.1 判断单价是否符合规格*/
          //进行空值还原，防止数据类型错误
          if(this.goodsList.price===""){
            this.goodsList.price=null
          }
          //判断价格是否为空
          if(this.goodsList.price!=null && self.goFunction){
            //判断是否含有非法字符
            if(this.goodsList.price.split(" ").length==1){
              //判断价格是否是符合规格的正数
              var reg = /^\d+(?=\.{0,1}\d+$|$)/
              //判断是否是正数数值型
              if(!reg.test(this.goodsList.price) || Number(this.goodsList.price)===0){
                //不符合规格不允许执行查询方法
                self.goFunction = false
                self.$message({
                  duration: 1500,
                  message: "价格不符合规格!",
                  type: "error",
                  onClose: function() {
                    self.loadStatus = false
                  },
                });
              }
            }else{
              //不符合规格不允许执行查询方法
              self.goFunction = false
              self.$message({
                duration: 1500,
                message: "价格文本框中存在非法字符空格!",
                type: "error",
                onClose: function() {
                  self.goodsList.price = ""
                  self.loadStatus = false
                },
              });
            }
          }
          /* 2.2 判断规格是否符合规格*/
          //进行空值还原，防止数据类型错误
          if(this.goodsList.specification===""){
            this.goodsList.specification=null
          }
          //判断商品规格是否是符合规格的正数
          if(this.goodsList.specification!=null && self.goFunction){
            var speReg = /(^[1-9]\d*$)/
            //判断是否含有非法字符
            if(this.goodsList.specification.split(" ").length==1){
              //判断是否是正整数数值型
              if(!speReg.test(this.goodsList.specification) || Number(this.goodsList.specification)===0){
                //不符合规格不允许执行查询方法
                self.goFunction = false
                self.$message({
                  duration: 1500,
                  message: "规格不符合规格!",
                  type: "error",
                  onClose: function() {
                    self.loadStatus = false
                  },
                });
              }
            }else{
              //不符合规格不允许执行查询方法
              self.goFunction = false
              self.$message({
                duration: 1500,
                message: "规格文本框中存在非法字符空格!",
                type: "error",
                onClose: function() {
                  self.goodsList.specification = ""
                  self.loadStatus = false
                },
              });
            }
          }


        }else{
          //不符合规格不允许执行查询方法
          self.goFunction = false
          self.$message({
            duration: 1500,
            message: "用户名中存在非法字符空格!",
            type: "error",
            onClose: function() {
              self.goodsList.goodsName=""
              self.loading = false;
            },
          });
        }

        //是否允许执行查询方法
        if(self.goFunction){
            let formData = new FormData()
            // 在formData中加入我们需要的参数
            formData.append('file', param.file)
            formData.append('goods', JSON.stringify(this.goodsList))
            // formData.append('classify', JSON.stringify())
            console.log("开始向后端发送请求")
            // 向后端发送数据
            self.$http.post('/api/CakeShop/GoodsManage/addGoods', formData).then((res) => {
              console.log(res)
              //判断数据是否存在
              if(res.data.exist===0){
                if (res.data.addSuccNum>0) {
                  self.$message({
                    message: res.data.msg,
                    type: 'success',
                    onClose: function() {
                      //添加完毕后清楚文本框中内容
                      self.clearData()
                      //关闭修改界面
                      self.closeAddGoods()
                      //添加完数据返回首页
                      self.$parent.getGoodsList(page)
                    }
                  });
                }else{
                  self.$message({
                    duration: 1500,
                    message: res.data.msg,
                    type: "error",
                    onClose: function() {
                      self.loading = false;
                    },
                  });
                }
              }else{
                self.$message({
                	duration: 1500,
                	message: res.data.msg,
                	type: "error",
                	onClose: function() {
                		self.loading = false;
                	},
                });
              }
            })


        }
      },
    },
  }
</script>

<style>
</style>
